﻿using UnityEngine;

[RequireComponent(typeof(BoxCollider2D))]
//给Fan一个子物体，并令其挂在此脚本，声音和有风区域重合
public class Wind : MonoBehaviour
{
    private Character player;
    private AudioPlayer AudioPlayer;

    private float maxSpeed_New;         //气流区域中对玩家的新限速
    [SerializeField]
    private Vector2 direction;
    [SerializeField]
    private float force;                //重力加速度为30

    private MyAudioSource m_audioSource;

    private void Awake()
    {
        player = Character.Instance;
        AudioPlayer = Service.Get<AudioPlayer>();
        maxSpeed_New = force;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.GetComponent<Character>() != null)
        {
            m_audioSource = AudioPlayer.CreateAudio("AudioSource/fx_wind",transform);
            player.InWindArea = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.GetComponent<Character>() != null)
        {
            m_audioSource.Stop();
            player.InWindArea = false;
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.GetComponent<Character>() != null)
        {
            player.InWindArea = true;
            collision.attachedRigidbody.AddForce((maxSpeed_New - collision.attachedRigidbody.velocity.magnitude) * force * direction / maxSpeed_New, ForceMode2D.Force);
        }
    }
}
